package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.model.entity.CabinetLoadPlanDetail;
import com.wing.cabinet.model.response.CabinetLoadPlanDetailVO;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.product.model.response.ProductPackLabelVO;
import com.wing.order.dao.OrderReceiveDao;
import com.wing.order.model.entity.*;
import com.wing.order.model.request.OrderReceiveForm;
import com.wing.order.model.response.DistributionDemandDetailVO;
import com.wing.order.model.response.InventoryJobLabelVO;
import com.wing.order.model.response.OrderDistributionLabelVO;
import com.wing.order.model.response.OrderReceiveVO;
import com.wing.warehouse.model.response.PalletBoxListVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 领货单-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class OrderReceiveServiceImpl extends ServiceImpl<OrderReceiveDao, OrderReceive> implements OrderReceiveService {

    @Autowired
    private InventoryJobLabelService inventoryJobLabelService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private OrderReceiveDetailService orderReceiveDetailService;

    @Override
    public int add(OrderReceiveForm orderReceiveForm) {

        //校验

        OrderReceive orderReceive =new OrderReceive();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(OrderReceive.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderReceiveForm, orderReceive, copyOptions);

        return baseMapper.insert(orderReceive);
    }

    @Override
    public List<OrderReceiveVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<OrderReceiveVO> pageList4app(Page page, Map<String, Object> params) {
        List<OrderReceiveVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<OrderReceiveVO> pageListLoading4app(Page page, Map<String, Object> params) {
        List<OrderReceiveVO> list = baseMapper.listLoading4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public OrderReceiveVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public void receive(Long id) {
        InventoryJobLabelVO orderDistributionLabelVO=inventoryJobLabelService.get4appById(id);
        if (orderDistributionLabelVO==null){
            throw new BusinessException("未找到业务数据");
        }
        InventoryJobLabel orderDistributionLabel=new InventoryJobLabel();
        orderDistributionLabel.setId(id);
        orderDistributionLabel.setStatus(InventoryJobLabel.Status.receive);
        inventoryJobLabelService.updateById(orderDistributionLabel);

    }

    @Override
    @Transactional
    public void save(OrderReceiveForm orderReceiveForm) {
        Long creator= JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        OrderReceive orderReceive=new OrderReceive();
        BeanUtils.copyProperties(orderReceiveForm,orderReceive);
        String code=dynamicService.getDayNextCode("ord_order_receive");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String day=simpleDateFormat.format(new Date());
        orderReceive.setDay(Integer.valueOf(day));
        orderReceive.setNo(Integer.valueOf(code));
        orderReceive.setCode("RE-"+day+"-"+code);
        orderReceive.setTaskCode("TA-"+day+"-"+code);
        orderReceive.setLoadCode("LO-"+day+"-"+code);
        orderReceive.setCreator(creator);
        orderReceive.setCreatorName(creatorName);
        baseMapper.insert(orderReceive);
        Long receiveId=orderReceive.getId();
        if (CollectionUtils.isEmpty(orderReceiveForm.getLoadPlanDetailList())){
            throw new BusinessException("缺少领货明细数据");
        }

        Map<String,Long> skuCodeMap=new HashMap<>();
        for (CabinetLoadPlanDetailVO loadPlanDetailVO:orderReceiveForm.getLoadPlanDetailList()){
            OrderReceiveDetail orderReceiveDetail=new OrderReceiveDetail();
            orderReceiveDetail.setCreator(creator);
            orderReceiveDetail.setCreatorName(creatorName);
            orderReceiveDetail.setSkuCode(loadPlanDetailVO.getSkuCode());
            orderReceiveDetail.setDemandId(loadPlanDetailVO.getDistributionDemandId());
            orderReceiveDetail.setDemandDetailId(loadPlanDetailVO.getDistributionDemandDetailId());
            orderReceiveDetail.setQuantity(loadPlanDetailVO.getQuantity().intValue());
            orderReceiveDetail.setLoadPlanId(loadPlanDetailVO.getCabinetLoadPlanId());
            orderReceiveDetail.setLoadPlanDetailId(loadPlanDetailVO.getId());
            orderReceiveDetail.setReceiveId(receiveId);

            orderReceiveDetailService.save(orderReceiveDetail);
            skuCodeMap.put(loadPlanDetailVO.getSkuCode(),orderReceiveDetail.getId());
        }

        if (CollectionUtils.isEmpty(orderReceiveForm.getLabelList())){
            throw new BusinessException("缺少领货条码数据");
        }
        for (InventoryJobLabelVO inventoryJobLabelVO:orderReceiveForm.getLabelList()){
            InventoryJobLabel inventoryJobLabel=new InventoryJobLabel();
            inventoryJobLabel.setId(inventoryJobLabelVO.getId());
            inventoryJobLabel.setStatus(InventoryJobLabel.Status.receive);
            inventoryJobLabel.setReceiveId(receiveId);
            inventoryJobLabel.setReceiveDetailId(skuCodeMap.get(inventoryJobLabelVO.getSkuCode()));
            inventoryJobLabel.setReceiveTime(LocalDateTime.now());
            inventoryJobLabel.setReceiveId(creator);
            inventoryJobLabel.setReceiverName(creatorName);
            inventoryJobLabelService.updateById(inventoryJobLabel);
        }
//
    }


    @Override
    @Transactional
    public void save4app(OrderReceiveForm orderReceiveForm) {
        Long creator= JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        OrderReceive orderReceive=new OrderReceive();
        BeanUtils.copyProperties(orderReceiveForm,orderReceive);
        String code=dynamicService.getDayNextCode("ord_order_receive");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String day=simpleDateFormat.format(new Date());
        orderReceive.setDay(Integer.valueOf(day));
        orderReceive.setNo(Integer.valueOf(code));
        orderReceive.setCode("RE-"+day+"-"+code);
        orderReceive.setTaskCode("TA-"+day+"-"+code);
        orderReceive.setLoadCode("LO-"+day+"-"+code);
        orderReceive.setCreator(creator);
        orderReceive.setCreatorName(creatorName);
        baseMapper.insert(orderReceive);
        Long receiveId=orderReceive.getId();
        if (CollectionUtils.isEmpty(orderReceiveForm.getLoadPlanDetailList())){
            throw new BusinessException("缺少领货明细数据");
        }

        Map<String,Long> skuCodeMap=new HashMap<>();

        if (CollectionUtils.isEmpty(orderReceiveForm.getLabelList())){
            throw new BusinessException("缺少领货条码数据");
        }
        for (InventoryJobLabelVO inventoryJobLabelVO:orderReceiveForm.getLabelList()){
            Long receiveDetailId=skuCodeMap.get(inventoryJobLabelVO.getSkuCode());
            if(receiveDetailId==null){
                OrderReceiveDetail orderReceiveDetail=new OrderReceiveDetail();
                orderReceiveDetail.setCreator(creator);
                orderReceiveDetail.setCreatorName(creatorName);
                orderReceiveDetail.setSkuCode(inventoryJobLabelVO.getSkuCode());
                orderReceiveDetail.setDemandId(inventoryJobLabelVO.getDemandId());
                orderReceiveDetail.setDemandDetailId(inventoryJobLabelVO.getDemandDetailId());
                orderReceiveDetail.setQuantity(inventoryJobLabelVO.getQuantity().intValue());
                orderReceiveDetail.setLoadPlanId(inventoryJobLabelVO.getLoadPlanId());
                orderReceiveDetail.setLoadPlanDetailId(inventoryJobLabelVO.getLoadPlanDetailId());
                orderReceiveDetail.setReceiveId(receiveId);

                orderReceiveDetailService.save(orderReceiveDetail);
                skuCodeMap.put(inventoryJobLabelVO.getSkuCode(),orderReceiveDetail.getId());
            }
            InventoryJobLabel inventoryJobLabel=new InventoryJobLabel();
            inventoryJobLabel.setId(inventoryJobLabelVO.getId());
            inventoryJobLabel.setStatus(InventoryJobLabel.Status.receive);
            inventoryJobLabel.setReceiveId(receiveId);
            inventoryJobLabel.setReceiveDetailId(skuCodeMap.get(inventoryJobLabelVO.getSkuCode()));
            inventoryJobLabel.setReceiveTime(LocalDateTime.now());
            inventoryJobLabel.setReceiveId(creator);
            inventoryJobLabel.setReceiverName(creatorName);
            inventoryJobLabelService.updateById(inventoryJobLabel);
        }
//
    }

    @Override
    @Transactional
    public void receiveSubmit(List<InventoryJobLabel> list) {
        Long creator= JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        OrderReceive orderReceive=new OrderReceive();
        String code=dynamicService.getDayNextCode("ord_order_receive");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String day=simpleDateFormat.format(new Date());
        orderReceive.setDay(Integer.valueOf(day));
        orderReceive.setNo(Integer.valueOf(code));
        orderReceive.setCode("RE-"+day+"-"+code);
        orderReceive.setTaskCode("TA-"+day+"-"+code);
        orderReceive.setLoadCode("LO-"+day+"-"+code);
        orderReceive.setDemandId(list.get(0).getDemandId());
        orderReceive.setLoadPlanId(list.get(0).getLoadPlanId());
        orderReceive.setType(list.get(0).getLoadType());
        orderReceive.setCreator(creator);
        orderReceive.setCreatorName(creatorName);
        orderReceive.setStatus(OrderReceive.Status.created);
        baseMapper.insert(orderReceive);
        Long receiveId=orderReceive.getId();
        Map<String,Long> receiveDetailIdMap=new HashMap<>();
        for (InventoryJobLabel orderReceiveLabel:list){

//            List<OrderReceiveLabel> orderReceiveLabels=baseMapper.selectList(new QueryWrapper<OrderReceiveLabel>().eq("demand_id",orderReceiveLabel.getDemandId()).eq("pack_label_code",orderReceiveLabel.getPackLabelCode()));
            Map paramMap=new HashMap();
            paramMap.put("packLabelCode",orderReceiveLabel.getPackLabeCode());
            paramMap.put("loadPlanDetailId",orderReceiveLabel.getLoadPlanDetailId());
            List<InventoryJobLabelVO> labelVOS=inventoryJobLabelService.list4app(paramMap);
            if (labelVOS.size()==0){
                throw new BusinessException("未找到此上货计划已出库的包装条码");
            }
            InventoryJobLabelVO inventoryJobLabelVO=labelVOS.get(0);
            if (InventoryJobLabel.Status.receive.equals(inventoryJobLabelVO.getStatus())){
                throw new BusinessException("此包装条码已领货");
            }

            if (!receiveDetailIdMap.containsKey(orderReceiveLabel.getSkuCode())){
                OrderReceiveDetail orderReceiveDetail=new OrderReceiveDetail();
                orderReceiveDetail.setCreator(creator);
                orderReceiveDetail.setCreatorName(creatorName);
                orderReceiveDetail.setSkuCode(orderReceiveLabel.getSkuCode());
                orderReceiveDetail.setDemandId(orderReceiveLabel.getDemandId());
                orderReceiveDetail.setDemandDetailId(orderReceiveLabel.getDemandDetailId());
                orderReceiveDetail.setQuantity(orderReceiveLabel.getQuantity().intValue());
                orderReceiveDetail.setReceiveId(receiveId);

                orderReceiveDetail.setLoadPlanId(orderReceiveLabel.getLoadPlanId());
                orderReceiveDetail.setLoadPlanDetailId(orderReceiveLabel.getLoadPlanDetailId());
                orderReceiveDetail.setStatus(OrderReceiveDetail.Status.created);
//                List<OrderReceiveDetail> orderReceiveDetails=orderReceiveDetailService.list(new QueryWrapper<OrderReceiveDetail>().eq("demand_id",orderReceiveLabel.getDemandId()).eq("sku_code",orderReceiveLabel.getSkuCode()));
//                if (orderReceiveDetails.size()==0){
                orderReceiveDetailService.save(orderReceiveDetail);
                receiveDetailIdMap.put(orderReceiveLabel.getSkuCode(),orderReceiveDetail.getId());
//                }else{
//                    receiveDetailIdMap.put(orderReceiveLabel.getSkuCode(),orderReceiveDetails.get(0).getId());
//                }

                InventoryJobLabel inventoryJobLabel=new InventoryJobLabel();
                inventoryJobLabel.setId(orderReceiveLabel.getId());
                inventoryJobLabel.setStatus(InventoryJobLabel.Status.receive);
                inventoryJobLabel.setReceiveId(receiveId);
                inventoryJobLabel.setReceiveDetailId(orderReceiveDetail.getId());
                inventoryJobLabel.setReceiveTime(LocalDateTime.now());
                inventoryJobLabel.setReceiveId(creator);
                inventoryJobLabel.setReceiverName(creatorName);
                inventoryJobLabel.setLoadPlanId(orderReceiveLabel.getLoadPlanId());
                inventoryJobLabel.setLoadPlanDetailId(orderReceiveLabel.getLoadPlanDetailId());
                inventoryJobLabel.setDemandId(orderReceiveLabel.getDemandId());
                inventoryJobLabel.setDemandDetailId(orderReceiveLabel.getDemandDetailId());
                inventoryJobLabelService.updateById(inventoryJobLabel);
            }

//            JsonResult<ProductPackLabelVO> jsonResult=enterpriseClient.getProductPackLabelVOList(orderReceiveLabel.getPackLabelCode(),0);
//            ProductPackLabelVO labels=jsonResult.getData();
//            if (labels==null){
//                throw new BusinessException("未找到包装条码");
//            }
//            if (labels.getSurplusQuantity().intValue()<orderReceiveLabel.getQuantity().intValue()){
//                throw new BusinessException("领取数量不能大于包装条码对应的数量");
//            }
//
////            enterpriseClient.updateProductPackLabe(orderReceiveLabel.getPackLabelId(),orderReceiveLabel.getQuantity().intValue());
//
//            enterpriseClient.extractPackLabel(orderReceiveLabel.getPackLabelCode(),orderReceiveLabel.getQuantity().intValue(),1);
//
//            DistributionDemandDetailVO distributionDemandDetail=distributionDemandDetailService.get4appById(orderReceiveLabel.getDemandDetailId());
//            if (distributionDemandDetail==null){
//                throw new BusinessException("未找到配货需求单明细数据");
//            }
//            Integer quantitySurplus=distributionDemandDetail.getQuantityConfirm().intValue();
//            if (distributionDemandDetail.getQuantityReceive()!=null){
//                quantitySurplus=quantitySurplus-distributionDemandDetail.getQuantityReceive();
//            }
//            quantitySurplus=quantitySurplus-orderReceiveLabel.getQuantity().intValue();
//            if (quantitySurplus<0){
//                throw new BusinessException("领货数不能大于配货需求确认数");
//            }
//
//            if (quantitySurplus==0){
//                DistributionDemandDetail distributionDemandDetail4Update=new DistributionDemandDetail();
//                distributionDemandDetail4Update.setId(distributionDemandDetail.getId());
//                distributionDemandDetail4Update.setStatus(DistributionDemandDetail.Status.finish);
//                distributionDemandDetailService.updateById(distributionDemandDetail4Update);
//            }
//
//            PalletBoxListVO palletBoxListVO=boxListService.getPalletBoxByLabelCode(orderReceiveLabel.getPackLabelCode());
//            if (palletBoxListVO!=null){
//                orderReceiveLabel.setWarehouseId(palletBoxListVO.getWarehouseId());
//                orderReceiveLabel.setAreaId(palletBoxListVO.getAreaId());
//                orderReceiveLabel.setShelfId(palletBoxListVO.getShelfId());
//                orderReceiveLabel.setSpaceId(palletBoxListVO.getSpaceId());
//            }
//
//            orderReceiveLabel.setReceiveId(receiveId);
//            orderReceiveLabel.setReceiveDetailId(receiveDetailIdMap.get(orderReceiveLabel.getSkuCode()));
//            orderReceiveLabel.setCreator(creator);
//            orderReceiveLabel.setCreatorName(creatorName);
//            baseMapper.insert(orderReceiveLabel);
        }

//        int count=distributionDemandDetailService.countNotFinish(list.get(0).getDemandId());
//        if (count==0){
//            DistributionDemand distributionDemand=new DistributionDemand();
//            distributionDemand.setId(list.get(0).getDemandId());
//            distributionDemand.setStatus(DistributionDemand.Status.finish);
//            distributionDemandService.updateById(distributionDemand);
//        }
    }
}
